<template>
  <!--工艺执行详情-->
  <div class="app-container">

    <el-row :gutter="20">

      <!-- 工艺树（左侧） -->
      <el-col :span="5" :xs="24">
        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span>工艺树</span>
            <el-button style="float: right; padding: 3px 0" type="text">+</el-button>
          </div>
          <el-tree
            :data="processTree"
            :props="defaultProps_processTree"
            :expand-on-click-node="false"
            ref="tree"
            default-expand-all
            :render-content="renderTree"
          />
        </el-card>
      </el-col>

      <!-- 生产任务详情（右侧） -->
      <el-col :span="19" :xs="24">

        <!-- （右1）基本信息 -->
        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span class="mr20"><b>基本信息</b></span>
            <el-tooltip content="添加子节点" placement="top">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="showDialog_processExec()"
                v-hasPermi="['mes:process:add']"
              >添加
              </el-button>
            </el-tooltip>
            <el-tooltip content="修改当前节点" placement="top">
              <el-button
                type="success"
                plain
                icon="el-icon-check"
                size="mini"
                @click="showDialog_processExec(currUuid)"
                v-hasPermi="['mes:process:add']"
              >修改
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除非根节点" placement="top">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                @click="del_processExec"
                v-hasPermi="['mes:process:add']"
              >删除
              </el-button>

            </el-tooltip>
            <el-tooltip content="打印当前节点信息" placement="top">
              <el-button
                type="info"
                plain
                size="mini"
                @click="open_print"
                icon="el-icon-printer"
                v-print="'#printTest'"
              >打印
              </el-button>
            </el-tooltip>
            <el-tooltip content="显示 / 隐藏" placement="top" style="float: right; padding: 3px 0">
              <el-switch
                v-model="fold_form_basic"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="false"
                inactive-value="true">
              </el-switch>
            </el-tooltip>
          </div>

          <div v-show="fold_form_basic == 'false'">
            <el-form ref="form_basic" :model="form_basic" label-width="80px">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="序号">
                    {{form_basic.orderNum}}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="版本号">
                    {{form_basic.versionNum}}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="图纸号">
                    {{form_basic.drawNum}}
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="零件号">
                    {{form_basic.partNum}}
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="物料">
                    {{form_basic.selectedItem}}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="执行数量">
                    {{form_basic.execQty}}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="计量单位">
                    <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="form_basic.wmsDictMeasuringUnit"/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="编号">
                    {{form_basic.docNum}}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="单据时间">
                    {{form_basic.docDt}}
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="经办人">
                    {{form_basic.selectedAttentionUser}}
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

          </div>
        </el-card>

        <!-- 物料清单-物料列表（右2） -->
        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">

          <div slot="header" class="clearfix">
            <span><b>物料清单</b></span>
            <el-tooltip content="显示 / 隐藏" placement="top" style="float: right; padding: 3px 0">
              <el-switch
                v-model="fold_process_items"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="false"
                inactive-value="true">
              </el-switch>
            </el-tooltip>
          </div>

          <el-collapse-transition>
            <el-row v-show="fold_process_items == 'false'">
              <!-- 按钮：新增物料 -->
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="dialog_show_processItem"
                    v-hasPermi="['mes:process:add']"
                  >新增物料
                  </el-button>
                </el-col>
              </el-row>
              <!-- 列表：物料 -->
              <el-table
                v-loading="loading"
                :data="itemList"
                row-key="taskItemUuid"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55" align="center"/>
                <el-table-column label="序号" align="center" prop="orderNum" width="80"/>
                <el-table-column label="物料名称" align="center" prop="itemName" width="240" :show-overflow-tooltip="true"/>
                <el-table-column label="物料编码" align="center" prop="itemNum" width="160"/>
                <el-table-column label="规格" align="center" prop="itemSpecification" width="120"/>
                <el-table-column label="数量" align="center" prop="itemQty" />
                <el-table-column label="备件数量" align="center" prop="itemBakQty" />
                <el-table-column label="状态" align="center" prop="sysNormalDisable" >
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.sysNormalDisable"/>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="update_item(scope.row)"
                      v-hasPermi="['mes:process:edit']"
                    >修改
                    </el-button>
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="del_item(scope.row)"
                      v-hasPermi="['mes:process:remove']"
                    >删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-show="total_items>0"
                :total="total_items"
                :page.sync="queryParams_task.pageNum"
                :limit.sync="queryParams_task.pageSize"
                @pagination="getList_items"
              />
            </el-row>
          </el-collapse-transition>
        </el-card>

        <!-- 工序清单-工序列表（右3） -->
        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span><b>工序清单</b></span>
          </div>
          <!-- 按钮：新增工序 -->
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="dialog_show_processDetail"
                v-hasPermi="['mes:taskDetails:add']"
              >新增工序
              </el-button>
            </el-col>

          </el-row>
          <!-- 列表：工序 -->
          <el-table
            v-loading="loading"
            :data="detailsList"
            row-key="taskItemUuid"
            @selection-change="handleSelectionChange"

          >

            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="序号" align="center" prop="orderNum" width="50"/>
            <el-table-column label="工序号" align="center" prop="processCode" />

            <el-table-column label="工序符号" align="center" prop="mesDictProcessCode">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.mes_dict_process_code" :value="scope.row.mesDictProcessCode"/>
              </template>
            </el-table-column>
            <el-table-column label="工序类型" align="center" prop="mesDictProcessType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.mes_dict_process_type" :value="scope.row.mesDictProcessType"/>
              </template>
            </el-table-column>
            <el-table-column label="工序名称" align="center" prop="mesDictProcessName">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.mes_dict_process_name" :value="scope.row.mesDictProcessName"/>
              </template>
            </el-table-column>

            <el-table-column label="设备类型" align="center" prop="wmsDictDeviceType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.wms_dict_device_type" :value="scope.row.wmsDictDeviceType"/>
              </template>
            </el-table-column>

            <el-table-column label="工序内容" align="center" prop="processContent"/>
            <el-table-column label="标准定额" align="center" prop="quotaQtyMin"/>
            <el-table-column label="是否质检" align="center" prop="sysYesNoQc">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.sysYesNoQc"/>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="sysNormalDisable">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.sysNormalDisable"/>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="docNote"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="update_detail(scope.row)"
                  v-hasPermi="['mes:taskDetails:edit']"
                >修改
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete_detail(scope.row)"
                  v-hasPermi="['mes:taskDetails:remove']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total_details>0"
            :total="total_details"
            :page.sync="queryParams_details.pageNum"
            :limit.sync="queryParams_details.pageSize"
            @pagination="getList_details"
          />
        </el-card>

      </el-col>

    </el-row>

    <!-- 对话框（右1）：添加、修改 - 施工 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="dialog_title_processExec" :visible.sync="dialog_visible_processExec"
               width="800px" append-to-body :close-on-click-modal=false>

      <!-- 表单：工艺施工 -->
      <el-form ref="form_processExec" :model="form_processExec" :rules="rules_processExec" label-width="80px">

        <el-input v-show="false" v-model="form_processExec.processExecUuid"/>
        <el-input v-show="false" v-model="form_processExec.parentUuid"/>

        <el-row>
          <el-col :span="12">
            <el-form-item label="序号" prop="orderNum">
              <el-input v-model="form_processExec.orderNum" placeholder="请输入版本号" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="版本号" prop="versionNum">
              <el-input v-model="form_processExec.versionNum" placeholder="请输入版本号" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="图纸号" prop="drawNum">
              <el-input v-model="form_processExec.drawNum" placeholder="请输入图纸号" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="零件号" prop="partNum">
              <el-input v-model="form_processExec.partNum" placeholder="请输入零件号" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="物料" prop="fkItemUuid">
              <el-input v-model="form_processExec.fkItemUuid" v-show="false"/>
              <el-tooltip class="item" effect="dark" :content="form_processExec.selectedItem_tooltip" placement="top">
                <el-input placeholder="请选择" v-model="form_processExec.selectedItem" class="input-with-select"
                          :style="{width: '100%'}">
                  <el-button @click="dialog_show_selectItem(form_processExec)" slot="append"
                             icon="el-icon-search"></el-button>
                </el-input>
              </el-tooltip>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="数量" prop="execQty">
              <el-input-number v-model="form_processExec.execQty" placeholder="请输入数量" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="计量单位" prop="wmsDictMeasuringUnit">
              <el-select v-model="form_processExec.wmsDictMeasuringUnit" :style="{width: '100%'}"
                         placeholder="请选择计量单位" clearable size="small">
                <el-option
                  v-for="dict in dict.type.wms_dict_measuring_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="编号" prop="docNum">
              <el-input v-model="form_processExec.docNum" placeholder="请输入编号" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据时间" prop="docDt">
              <el-date-picker clearable size="small"
                              v-model="form_processExec.docDt"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm"
                              placeholder="选择单据时间"
                              :style="{width: '100%'}">
              </el-date-picker>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="经办人" prop="fkAttentionUserId">
              <el-input v-model="form_processExec.fkAttentionUserId" v-show="false"/>
              <el-input placeholder="请选择经办人" v-model="form_processExec.selectedAttentionUser" class="input-with-select"
                        :style="{width: '100%'}">
                <el-button @click="dialog_show_selectUser( form_processExec )" slot="append"
                           icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm_processExec">确 定</el-button>
        <el-button @click="hideDialog_processExec">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 对话框（右2）：添加、修改 - 物料 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="dialog_title_item"
               :visible.sync="dialog_visible_item" width="800px" append-to-body :close-on-click-modal=false>
      <el-form ref="form_item" :model="form_item" :rules="rules_item" label-width="100px">
        <el-input v-model="form_item.fkProcessExecUuid" v-show="false"/>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="orderNum">
          <span slot="label">
            排序序号
            <el-tooltip content="请设置显示顺序，默认值是 “1”，建议输入数字。" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
              <el-input v-model="form_item.orderNum" placeholder="请输入排序序号" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料" prop="fkItemUuid">
          <span slot="label">
            物料
            <el-tooltip :content="form_item.selectedItem_tooltip" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
              <el-input v-model="form_item.fkItemUuid" v-show="false"/>
              <el-input placeholder="请点击右侧查找按钮选择物料" v-model="form_item.selectedItem" class="input-with-select"
                        :style="{width: '100%'}">
                <el-button @click="dialog_show_selectItem(form_item)"
                           slot="append" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="数量" prop="itemQty">
              <el-input v-model="form_item.itemQty" placeholder="请输入数量" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备件数量" prop="itemBakQty">
              <el-input v-model="form_item.itemBakQty" placeholder="请输入备件数量" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form_item.sysNormalDisable">
                <el-radio
                  v-for="dict in statusOptions_item"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="docNote">
              <el-input v-model="form_item.docNote" autosize type="textarea" placeholder="请输入内容"
                        :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm_item">确 定</el-button>
        <el-button @click="hideDialog_processExecItem">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 对话框（右3）：添加、修改 - 工序 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="dialog_title_detail" :visible.sync="dialog_visible_detail"
               width="750px" append-to-body :close-on-click-modal=false>
      <el-form ref="form_detail" :model="form_detail" :rules="rules_detail" label-width="100px">
        <!-- 工艺规程ID-->
        <el-input v-model="form_detail.fkProcessExecUuid" v-show="false"/>

        <el-row>
          <el-col :span="12">
            <el-form-item label="排序序号" prop="orderNum">
              <el-input v-model="form_detail.orderNum" placeholder="请输入排序序号" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工序号" prop="processCode">
              <el-input v-model="form_detail.processCode" placeholder="请输入工序号" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工序类型" prop="mesDictProcessType">
              <el-select v-model="form_detail.mesDictProcessType" placeholder="请选择工序类型" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.mes_dict_process_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工序名称" prop="mesDictProcessName">
              <el-select v-model="form_detail.mesDictProcessName" placeholder="请选择工序名称" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.mes_dict_process_name"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工序符号" prop="mesDictProcessCode">
              <el-select v-model="form_detail.mesDictProcessCode" placeholder="请选择工序符号" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.mes_dict_process_code"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="设备类型" prop="wmsDictDeviceType">
              <el-select v-model="form_detail.wmsDictDeviceType" placeholder="请选择设备类型"  :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.wms_dict_device_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="工序内容">
              <editor v-model="form_detail.processContent" :min-height="192" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>



          <el-col :span="12">
            <el-form-item label="是否质检">
              <el-radio-group v-model="form_detail.sysYesNoQc">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form_detail.sysNormalDisable">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="quotaQtyMin">
               <span slot="label">
                标准定额
                  <el-tooltip content="标准定额单位(分钟)" placement="top">
                    <i class="el-icon-question"></i>
                 </el-tooltip>
              </span>
              <el-input v-model="form_detail.quotaQtyMin" placeholder="请输入标准定额" :style="{width: '100%'}">
                <template slot="append">分钟</template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="docNote">
              <el-input v-model="form_detail.docNote" type="textarea" autosize placeholder="请输入内容"
                        :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm_detail">确 定</el-button>
        <el-button @click="hideDialog_processExecDetail">取 消</el-button>
      </div>
    </el-dialog>

    <select-user ref="component_selectUser" @ok="selectUser_done"/>
    <select-item ref="component_selectItem" @ok="selectItem_done"/>

    <div  id="printTest">
      <el-dialog :visible.sync="openPrint" width="1600px" :show-close="false">
      <el-form ref="form_basic" :model="form_basic" label-width="100px">
        <el-row>
          <el-divider content-position="left"><h2>订单信息</h2></el-divider>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="销售号">
              {{form_basic.orderDocNum}}
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="订单时间">
              {{parseTime(form_basic.orderDocDt, '{y}-{m}-{d} {h}:{i}')}}
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="客户名称">
              {{form_basic.custName}}
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="订单金额(￥)">
              {{retainTwo(form_basic.orderAmt)}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-divider content-position="left"><h2>产品信息</h2></el-divider>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="产品名称">
              {{form_basic.orderItemName}}
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="产品数量">
              {{form_basic.orderDetailQty}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计量单位">
              <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="form_basic.orderUnit"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单价">
              {{retainSix(form_basic.orderDetailAmt)}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-divider content-position="left"><h2>零件信息</h2></el-divider>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="零件名称">
              {{form_basic.itemName}}
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="零件编码">
              {{form_basic.itemNum}}
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="零件号">
              {{form_basic.partNum}}
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="图纸号">
              {{form_basic.drawNum}}
            </el-form-item>
          </el-col>


        </el-row>
      </el-form>
      <el-table :data="detailsList" border>
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="序号" align="center" prop="orderNum" width="50"/>
        <el-table-column label="工序名称" align="center" prop="mesDictProcessName" width="252">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_dict_process_name" :value="scope.row.mesDictProcessName"/>
          </template>
        </el-table-column>
        <el-table-column label="工序内容" align="center" prop="processContent" width="300"/>
        <el-table-column label="工人" align="center" prop="worker" width="300"/>
        <el-table-column label="是否质检" align="center" prop="sysYesNoQc" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.sysYesNoQc"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="docNote" width="500"/>
      </el-table>
      </el-dialog>
    </div>
  </div>

</template>
<script>
import {getProcessExec, delProcessExec, updateProcessExec, addProcessExec} from "@/api/mes/processExec";
import {listTaskDetails, getTaskDetails, delTaskDetails, addTaskDetails, updateTaskDetails} from "@/api/mes/taskDetails";
import {listTaskItems, getTaskItems, addTaskItems, updateTaskItems, delItems} from "@/api/mes/taskItems";
import selectUser from "../../system/user/selectUser";
import selectItem from "../../wms/wmsItems/selectItem";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {treeSelect_processExec} from "@/api/mes/processExec";
import{newDocNum} from "@/api/oa/docNum";
import {parseTime} from "@/utils/ruoyi";

  export default {
    dicts: ['sys_normal_disable', 'mes_dict_process_type', 'mes_dict_process_name',
      'mes_dict_process_code', 'sys_yes_no', 'wms_dict_measuring_unit','wms_dict_device_type'],
    name: "Process",
    components: {Treeselect, selectUser, selectItem},
    data() {
      return {
        openPrint: false,
        taskUuid: '', // 生产任务 UUID（参数）
        fold_form_basic: 'false',
        fold_process_items: 'false',
        rootUuid: '', // 工艺树根节点
        currUuid: '', // 当前工艺ID
        currForm: '', // 当前表单
        dialog_title_processExec: '', // 对话框标题：工序
        dialog_title_item: "", // 弹出层标题：物料
        dialog_title_detail: '', // 对话框标题：工序明细
        dialog_visible_processExec: false, // 对话框是否可见：工序
        dialog_visible_item: false,
        dialog_visible_detail: false,

        processTree: undefined, // 工艺树
        loading: true, // 遮罩层
        showSearch: true, // 显示搜索条件
        total: 0, // 总条数
        total_items: 0, // 总条数
        total_details: 0, // 总条数
        measuringUnitOptions: [],
        processList: [], // 工艺规程表格数据
        itemList: [],
        detailsList: [],
        title: "", // 弹出层标题
        statusOptions_item: [], // 状态选项：物料
        open: false, // 是否显示弹出层
        // 查询参数
        queryParams_task: {
          ancestors: '',
          parentUuid: null,
          versionNum: null,
          drawNum: null,
          fkItemUuid: null,
          docNum: null,
          docDt: null,
          fkAttentionUserId: null,
        },
        // 查询参数
        queryParams_items: {},
        // 查询参数
        queryParams_details: {},
        // 表单参数
        form: {},
        form_item: {
          selectedItem: '',
          sysNormalDisable: null,
          fkItemUuid:null,
        },
        form_detail: {
        },
        form_processExec: {
          processExecUuid: null,
          parentUuid: null,
        },
        form_basic: {
          parentUuid: null,
          show: '1',
        },
        defaultProps_processTree: {
          children: "children",
          label: "label",
        },
        // 表单校验
        rules: {
          parentUuid: [
            {required: true, message: "父ID不能为空", trigger: "blur"}
          ],
          versionNum: [
            {required: true, message: "版本号不能为空", trigger: "blur"}
          ],
          fkItemUuid: [
            {required: true, message: "物料表ID不能为空", trigger: "blur"}
          ],

          docNum: [
            {required: true, message: "编号不能为空", trigger: "blur"}
          ],
          docDt: [
            {required: true, message: "单据时间不能为空", trigger: "blur"}
          ],
          fkAttentionUserId: [
            {required: true, message: "经办人ID不能为空", trigger: "blur"}
          ],
        },
        rules_processExec: {
          versionNum: [
            { required: true, message: "请选择工序符号", trigger: "change" }
          ],
          drawNum: [
            { required: true, message: "请选择工序名称", trigger: "change" }
          ],
          partNum: [
            { required: true, message: "请输入零件号", trigger: "change" }
          ],
          fkItemUuid: [
            { required: true, message: "请选择工序类型", trigger: "change" }
          ],
          docNum: [
            { required: true, message: "请选择工序符号", trigger: "change" }
          ],
          docDt: [
            { required: true, message: "请选择工序名称", trigger: "change" }
          ],
          fkAttentionUserId: [
            { required: true, message: "请选择工序类型", trigger: "change" }
          ],

        },
        rules_detail: {
          mesDictProcessName: [
            { required: true, message: "请选择工序名称", trigger: "change" }
          ],
          mesDictProcessType: [
            { required: true, message: "请选择工序类型", trigger: "change" }
          ],
        },
        rules_item: {
          fkProcessExecUuid: [
            {required: true, message: "工艺规程ID不能为空", trigger: "blur"}
          ],
          fkItemUuid: [
            {required: true, message: "请选择物料", trigger: "change"}
          ],
          itemQty: [
            {required: true, message: "请输入数量", trigger: "change"}
          ],
          itemBakQty: [
            {required: true, message: "请输入备件数量", trigger: "change"}
          ],
          sysNormalDisable: [
            {required: true, message: "状态不能为空", trigger: "blur"}
          ],
        },
      };
    },

    created() {
      // $route params
      this.rootUuid = this.$route.params && this.$route.params.processExecUuid;
      if (this.rootUuid) {
        this.currUuid = this.rootUuid
      }else console.log('！！！ 无参数 ！！！')

      /** sys_normal_disable */
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions_item = response.data;
      });

      /** 计量单位 */
      this.getDicts("wms_dict_measuring_unit").then(response => {
        this.measuringUnitOptions = response.data;
      });
      this.getTree(); // 树
    },
    methods: {

      retainTwo(val) {
        return Number(val).toFixed(2);
      },

      retainSix(val) {
        return Number(val).toFixed(6);
      },

      open_print(){
        this.openPrint = true
        setTimeout(()=>{
          this.openPrint = false
        },1000)
      },

      /**(1) Tree*/
      /** 1-1 get tree */
      getTree() {
        treeSelect_processExec({ancestors: this.rootUuid,}).then(response => {
          this.processTree = response.data
          console.log(this.processTree)
          this.clickTree(this.currUuid)
        });
      },

      /** 1-2 render tree */
      renderTree(h, { node, data, store }) {
        return (
          <span class="custom-tree-node">
            <span>
              <el-button size="mini" type="text" on-click={ () => this.clickTree(data.id) }>{node.label}</el-button>
              <el-button size="mini" type="text" on-click={ () => this.showDialog_processExec(data.id) }> + </el-button>
              <el-button size="mini" type="text" on-click={ () => this.remove(node, data) }> - </el-button>
            </span>
          </span>);
      },

      /** 1-3 click tree */
      clickTree(processExecUuid) {
        this.loading = true;
        this.currUuid = processExecUuid
        getProcessExec(processExecUuid).then(response => {
          this.form_basic = this.buildExec(response.data)
        });
        this.getList_items()
        this.getList_details()
      },

      /** 1-4 构建已选物料、经办人 */
      buildExec(exec){
        exec.selectedItem = `${exec.itemName}（${exec.itemNum}）`
        exec.selectedAttentionUser = `${exec.attentionUserNickName}（${exec.fkAttentionUserId}）`
        return exec
      },

      /**(2) Basic*/
      /** 2-1 show dialog */
      showDialog_processExec(processExecUuid) {
        console.log(processExecUuid)
        this.resetForm_processExec()
        if(!processExecUuid){ // 添加子节点
          this.dialog_title_processExec = "添加子节点";
          this.form_processExec.parentUuid = this.currUuid
          newDocNum({preCode:'PRE-', len: 12}).then(response => {
            this.form_processExec.docNum = response.msg
          })
        }else{ // 修改当前节点
          this.dialog_title_processExec = "修改当前节点";
          this.$notify.info({ message: '正在加载工艺施工数据 ...' });
          getProcessExec(processExecUuid).then(response => {
            this.form_processExec = this.buildExec(response.data)
            this.$notify.success({ message: '加载工艺施工数据完成！' });
          });
        }
        this.dialog_visible_processExec = true
        this.form_processExec.selectedItem_tooltip = `请选择物料`
      },

      /** 2-2 hide dialog */
      hideDialog_processExec() {
        this.dialog_visible_processExec = false
      },

      /** 2-3 reset form */
      resetForm_processExec() {
        this.form_processExec = {
          processExecUuid: null,
          taskUuid: null,
          parentUuid: null,
          versionNum: null,
          drawNum: null,
          partNum: null,
          fkItemUuid: null,
          docNum: null,
          docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
          fkAttentionUserId: null,
        };
        this.resetForm("form_processExec");
      },

      /** 2-4 submit form */
      submitForm_processExec() {
        this.$refs["form_processExec"].validate(valid => {
          if (valid) {
            if (this.form_processExec.processExecUuid != null) { // 修改
              this.$notify.info({ message: '正在修改工艺施工数据 ...' });
              updateProcessExec(this.form_processExec).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.dialog_visible_processExec = false;
                this.getTree();
              });
            } else { // 添加
              this.$notify.info({ message: '正在新增工艺施工数据 ...' });
              addProcessExec(this.form_processExec).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.dialog_visible_processExec = false
                this.getTree();
              });
            }
          }
        });
      },

      /** 2-5 删除当前节点 */
      del_processExec() {
        this.$modal.msgSuccess("删除当前节点 ...");
        if (this.currUuid == this.rootUuid) {
          this.$alert('该页面不能删除根节点', '禁止删除', {
            confirmButtonText: '确定',
            type: 'error',
            callback: action => {
            }
          });
          return
        }
        console.log(this.form_basic)
        const ids = this.currUuid || this.ids;
        this.$modal.confirm(`是否确认删除 ${this.form_basic.selectedItem}的节点？`,'删除确认')
          .then(function () {
            return delProcessExec(ids);
          }).then(() => {
            this.$modal.msgSuccess("删除成功");
            this.getTree()
            this.clickTree(this.rootUuid)
          }).catch(() => {
        });
      },

      /**(3) items*/
      /** 3-1 获取列表：物料（已经调通） */
      getList_items() {
        this.loading = true;
        this.queryParams_items.fkProcessExecUuid = this.currUuid
        listTaskItems(this.queryParams_items).then(response => {
          this.itemList = response.rows;
          console.log( this.itemList )
          this.total_items = response.total;
          this.loading = false;
        });
      },

      /** 3-2 生产任务详情列表修改 - 物料（已经调通） */
      update_item(row) {
        console.log(row)
        this.form_reset_item();
        const processExecItemUuid = row.processExecItemUuid || this.ids
        getTaskItems(processExecItemUuid).then(response => {
          console.log(response)
          this.form_item = response.data;
          this.form_item.selectedItem = `${response.data.itemName}（编号：${response.data.itemNum}）`;
          this.dialog_visible_item = true;
          this.dialog_title_item = "修改工艺规程-工序明细";
        });
      },

      /** 3-3 生产任务物料清单删除物料按钮操作（已经调通） */
      del_item(row) {
        console.log(row)
        const ids = row.processExecItemUuid || this.ids;
        this.$modal.confirm(`是否确认删除序号为 ${row.orderNum} 的物料？`, '删除确认').then(function () {
          return delItems(ids);
        }).then(() => {
          this.getList_items();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },

      /** 获取列表：工序 （已经调通）*/
      getList_details() {
        this.loading = true;
        this.queryParams_details.fkProcessExecUuid = this.currUuid
        listTaskDetails(this.queryParams_details).then(response => {
          this.detailsList = response.rows;
          this.total_details = response.total;
          this.loading = false;
        });
      },

      /** 修改 - 工序清单 (已经调通)*/
      update_detail(row) {
        this.form_reset_detail();
        console.log(row)
        const uuid = row.processExecDetailUuid || this.ids
        getTaskDetails(uuid).then(response => {
          this.form_detail = response.data;
          this.dialog_visible_detail = true;
          this.dialog_title_detail = "修改工序清单";
        });
      },

      /** 工序清单列表删除按钮操作 (已经调通)*/
      handleDelete_detail(row) {
        console.log(row)
        const ids = row.processExecDetailUuid || this.ids;
        this.$modal.confirm(`是否确认删除序号为 ${row.orderNum} 的工序？`, '删除确认').then(function () {
          return delTaskDetails(ids);
        }).then(() => {
          this.getList_details();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },

      /**(5) dialog - process exec*/
      /**对话框 - 2*/
      /**表单重置：工艺*/
      form_reset_item() {
        this.form_item = {
          processExecItemUuid: null,
          fkProcessExecUuid: this.currUuid,
          sysNormalDisable: '0',
          orderNum: null,
          selectedItem_tooltip: '请选择物料',
          selectedItem: null,
          fkItemUuid: null,
          mesDictProcessName: null,
          itemQty: null,
          itemBakQty: null,
        };
        this.resetForm("form_item");
      },

      /** 对话框：显示 = 物料明细 */
      dialog_show_processItem() {
        this.form_item.fkProcessExecUuid = this.currUuid
        this.form_item.sysNormalDisable = '0'
        this.dialog_visible_item = true
        this.dialog_title_item = '新增工艺物料'
        this.form_item.selectedItem_tooltip = '请选择物料'
      },

      dialog_hide_item() {
        this.dialog_visible_item = false
        this.$refs["form_item"].resetFields()
      },

      /** 提交按钮 */
      submitForm_item() {
        this.$refs["form_item"].validate(valid => {
          if (valid) {
            if (this.form_item.processExecItemUuid != null) {
              updateTaskItems(this.form_item).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.dialog_visible_item = false;
                this.getList_items();
              });
            } else {
              addTaskItems(this.form_item).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.dialog_visible_item = false;
                this.getList_items();
              });
            }
          }
        });
      },

      /**对话框 - 3*/
      /**表单重置：工艺*/
      form_reset_detail() {
        this.form_detail = {
          fkProcessExecUuid: this.currUuid,
          processExecDetailUuid: null,
          orderNum: '1',
          mesDictProcessType: null,
          mesDictProcessName: null,
          mesDictProcessCode: null,
          processContent: null,
          sysYesNoCopy: "Y",
          sysYesNoQc: "Y",
          sysNormalDisable: "0",
          docNote: null
        };
        this.resetForm("form_detail");
      },

      /** 对话框：显示 = 工序明细 */
      dialog_show_detail() {
        this.form_reset_detail()
        this.$modal.msgSuccess("对话框：显示 = 工序明细 dialog_show_detail()");
        this.dialog_visible_detail = true
      },

      /** 生产任务详情工序明细对话框：显示 = 工序明细 （已经调通）*/
      dialog_show_processDetail() {
        this.form_reset_detail()
        this.dialog_visible_detail = true
      },

      hideDialog_processExecItem() {
        this.dialog_visible_item = false
        this.$refs["form_item"].resetFields()
      },

      dialog_hide_detail() {
        this.dialog_visible_detail = false
      },

      hideDialog_processExecDetail() {
        this.dialog_visible_detail = false
      },

      /** 提交按钮 */
      submitForm_detail() {
        this.$refs["form_detail"].validate(valid => {
          if (valid) {
            if (this.form_detail.processExecDetailUuid != null) {
              updateTaskDetails(this.form_detail).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.dialog_visible_detail = false;
                this.getList_details();
              });
            } else {
              addTaskDetails(this.form_detail).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.dialog_visible_detail = false;
                this.getList_details();
              });
            }
          }
        });
      },

      /**取消按钮*/
      cancel() {
        this.open = false;
        this.resetForm_processExec();
      },

      /**表单重置：工艺*/
      resetForm_processExecDetail() {
        this.form_processExecDetail = {
          taskDetaiUuid: null,
          fkProcessExecUuid: null,
          orderNum: null,
          mesDictProcessType: null,
          mesDictProcessName: null,
          mesDictProcessCode: null,
          processContent: null,
          sysYesNoCopy: "0",
          sysNormalDisable: "0",
          docNote: null
        };
        this.resetForm("dialog_title_processExecDetail");
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },

      /** 多选框：选中数据有变化 */
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.taskUuid)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },

      /** 新增按钮操作 */
      dialog_show_process(processUuid) {
        this.resetForm_processExec();
        if (processUuid != null) {
          this.form_processExec.parentUuid = processUuid;
        } else {
          this.form_processExec.parentUuid = this.currUuid;
        }
        this.dialog_visible_processExec = true;
        this.dialog_title_processExec = "新增工艺节点";
        this.form_processExec.selectedItem_tooltip = `请选择物料`
      },

      /** 打开物料选择弹窗 */
      dialog_show_selectItem(form) {
        if (!form) console.log('form is null!')
        this.currentForm = form
        this.$refs.component_selectItem.dialog_show_selectItem();
      },

      /**完成：选择物料*/
      selectItem_done(item) {
        this.currentForm.fkItemUuid = item.itemUuid
        console.log(this.currentForm.fkItemUuid)
        this.currentForm.selectedItem = `${item.itemName}（物料编码：${item.itemNum}）`
        // this.currentForm.selectedItem_tooltip = `物料的唯一标识：${item.itemUuid}`
      },

      /** 打开授权用户表弹窗 */
      dialog_show_selectUser(form) {
        this.currentForm = form
        this.$refs.component_selectUser.show();
      },

      /** 选择用户完成 */
      selectUser_done(user) {
        this.currentForm.fkAttentionUserId = user.userId
        this.currentForm.selectedAttentionUser = `${user.nickName}（用户名：${user.userName}，ID：${user.userId}）`
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        console.log(row)
        this.taskUuid = row.fkProcessExecUuid
        this.$modal.confirm('是否确认删除工艺规程编号为"' + this.taskUuid + '"的数据项？').then(function () {
          return delProcessExec(this.taskUuid);
        }).then(() => {
          this.getTree();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
    }
  };
</script>
